package com.jinzhi.jzweb.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.msg.WxPushServiceQcl;
import com.jinzhi.jzweb.domain.ExaminationBatchComSDO;
import com.jinzhi.jzweb.domain.ExaminationBatchDO;
import com.jinzhi.jzweb.domain.StuSignUpComDO;
import com.jinzhi.jzweb.pojo.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxmp.service.MpConfigService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * 
 * <pre>
 * 考生报名 第二次加密查看
 * </pre>
 * <small> 2023-05-05 08:52:02 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/stuSignUpComNum2Po")
public class StuSignUpComNum2PoController extends BaseController {
	@Autowired
	private StuSignUpComService stuSignUpComService;

	@Autowired
	private StuSignUpComService stuSignUpService;
	@Autowired
	private UserService userService;
	@Autowired
	private ExaminationBatchService examinationBatchService;
	@Autowired
	private ExaminationBatchComSService comSService;

	@GetMapping()
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpComNum2")
	String stuSignUpComNum2(Integer types,Integer permsType,Model model){
		model.addAttribute("types",types);
		model.addAttribute("permsType",permsType);
		return "jzweb/stuSignUpCom/stuSignUpComNum2Po";
	}


	/**
     * 赛场录入
	 * @param id
     * @param model
     * @return
     */
	@GetMapping("/num2/{id}")
	@RequiresPermissions("jzweb:stuSignUpCom:num2")
	String stuSignUpComEnter(@PathVariable("id") Long id,Model model){

		StuSignUpComDO stuSignUpComDO=	stuSignUpService.selectById(id);
		if(StringUtils.isNotBlank(stuSignUpComDO.getCourt2())){
			ExaminationBatchComSDO examinationBatchComDO = comSService.selectById(stuSignUpComDO.getCourt2());
			stuSignUpComDO.setCourt2(examinationBatchComDO.getName());
		}
		model.addAttribute("stuSignUpCom",stuSignUpComDO);
		return "jzweb/stuSignUpCom/num2Po";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:stuSignUpCom:num2")
	String edit(@PathVariable("id") Long id,Model model){
		StuSignUpComDO stuSignUpCom = stuSignUpComService.selectById(id);
		model.addAttribute("stuSignUpCom", stuSignUpCom);
		return "jzweb/stuSignUpCom/enterPo";
	}

	/**
	 * 实操第二次加密
	 * @param stuSignUpCom
	 * @return
	 */
	@Log("修改考生报名")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:stuSignUpCom:num2")
	public Result<String>  update( StuSignUpComDO stuSignUpCom){
		StuSignUpComDO stuSignUpComDO1=new StuSignUpComDO();
		String realityNm2 = "";
		if(stuSignUpCom.getPermsType()==1){
			realityNm2 = stuSignUpCom.getRealityNm2();
		} else if (stuSignUpCom.getPermsType()==2) {
			realityNm2 = stuSignUpCom.getRealityNm4();
		}
		stuSignUpCom.setRealityNm2(realityNm2);
		stuSignUpComDO1.setId(stuSignUpCom.getId());
		stuSignUpComDO1.setRealityNm2(stuSignUpCom.getRealityNm2());
		if(stuSignUpCom.getRealityNm2()==null){
			return  Result.fail("请录入第二次加密！");
		}

		StuSignUpComDO stuSignUpComDO1s=stuSignUpComService.selectById(stuSignUpCom.getId());
		if(stuSignUpCom.getPermsType()==1 && stuSignUpComDO1s.getRealityNm1()==null){
			return  Result.fail("请先录入第一次加密！");
		}
		else if(stuSignUpCom.getPermsType()==2 && stuSignUpComDO1s.getRealityNm3()==null){
			return  Result.fail("请先录入第一次加密！");
		}
	Wrapper<StuSignUpComDO> wrapper=new EntityWrapper<>();
		wrapper.eq("cbatch_id",stuSignUpComDO1s.getCbatchId());
		wrapper.eq("reality_um2",stuSignUpCom.getRealityNm2());
		List<StuSignUpComDO> list =	stuSignUpComService.selectList(wrapper);
			if(list.size()>0){
				for(StuSignUpComDO li:list){
					if(!li.getId().equals(stuSignUpCom.getId())){
						return Result.fail("第二次加密序号重复！");
					}
				}


			}
		stuSignUpComDO1.setDecrypt(0);
		boolean update = stuSignUpComService.updateById(stuSignUpComDO1);
		return update ? Result.ok() : Result.fail();
	}


	/**
	 * 第二次加密新增（理论）
	 * */
	@GetMapping("/add2")
	@RequiresPermissions("jzweb:stuSignUpCom:add2")
	String add2(){

//		model.addAttribute("certificateProfile", certificateNewsService.selByNewId());
		return "jzweb/certificates/add";
	}




	/**
	 * 下载导入模板
	 *
	 * @param response
	 */
	@RequestMapping("/downloadImportTemplate")
	@RequiresPermissions("jzweb:stuSignUpCom:import")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response) {
		List<StuSignUpComVo> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "考生报名信息导入模板", "考生报名信息导入模板", StuSignUpComVo.class, "考生报名信息导入模板", response);
	}


	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpCom")
	public Result<Page<StuSignUpComDO>> list(StuSignUpComDO stuSignUpComDTO,int pageNumber, int pageSize){
/*		if(stuSignUpComDTO.getEbatchId()==null) {
			if (StringUtils.isBlank(this.getUser().getTrack())) {
				//超管
				stuSignUpComDTO.setCbatchId(null);
			} else {
				//一级或者工作人员
				stuSignUpComDTO.setCbatchId(999L);
			}
		}*/
		Map map =new HashMap();
		map.put("competitionType",stuSignUpComDTO.getCompetitionType());
		map.put("cbatch_id",stuSignUpComDTO.getEbatchId());
		Page<StuSignUpComDO> page = stuSignUpComService.selectPageList(pageNumber, pageSize,map);
		// 查询列表数据
		return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:stuSignUpCom:add")
	String add1(){
	    return "jzweb/stuSignUpCom/add";
	}


	/**
	 * 第一次加密
	 * @param stuSignUpCom
	 * @return
	 */
	@Log("赛场录入")
	@ResponseBody
	@RequestMapping("/updateEnter")
	@RequiresPermissions("jzweb:stuSignUpCom:resetPwd")
	public Result<String>  updateEnter( StuSignUpComDO stuSignUpCom){


		StuSignUpComDO stuSignUpComDO1s=	stuSignUpComService.selectById(stuSignUpCom.getId());

		Wrapper<StuSignUpComDO> wrapper=new EntityWrapper<>();
		wrapper.eq("cbatch_id",stuSignUpComDO1s.getCbatchId());
		if (stuSignUpCom.getPermsType()==1){
			wrapper.eq("reality_um1",stuSignUpCom.getRealityNm1());
		} else if (stuSignUpCom.getPermsType()==2) {
			wrapper.eq("reality_um3",stuSignUpCom.getRealityNm3());
		}
		List<StuSignUpComDO> list =	stuSignUpComService.selectList(wrapper);
		if(list.size()>0){
				for(StuSignUpComDO li:list){
					if(!li.getId().equals(stuSignUpCom.getId())){
						return  Result.fail("加密序号重复！");
					}
				}

		}



		boolean update = stuSignUpComService.updateById(stuSignUpCom);
		return update ? Result.ok() : Result.fail();
	}



	
	@Log("删除考生报名")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUpCom:remove")
	public Result<String>  remove( Long id){
		stuSignUpComService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除考生报名")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUpCom:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		stuSignUpComService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}


	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importComError")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:stuSignUp:import")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考生报名导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("stuSignComUp" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}

	/**
	 * 考生信息导入
	 *
	 * @param file excel文件
	 */
	@Log("考生信息导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:stuSignUpCom:import")
	public Result<?> importExcel(HttpServletRequest req, @RequestParam("file") MultipartFile file, String cbatchId,Integer type) {
		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		//第二步--解析文件获得数据
		List<StuSignUpComVo> list = EasyPoiUtil.importExcel(file, 1, 1, StuSignUpComVo.class);
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}
		//---------------------------------验证数据并导入-----------------------------------------
		//数据该市行为第三行，第一行标题，第二行表头
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<StuSignUpComDO> upDOList = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			UserDO rrUserDo = null;
			UserDO rsUserDo = null;
			StringBuilder sb = new StringBuilder();
			//第一步验证是否存在空值
			if (StringUtils.isBlank(list.get(i).getName())) {
				sb.append("第" + (i + startRow) + "行姓名未填写，请完善！" + ";");
			} else {
//				if (StringUtils.isBlank(list.get(i).getSex())) {
//					sb.append("第" + (i + startRow) + "行性别未填写，请完善！" + ";");
//				} else {
				if (StringUtils.isBlank(list.get(i).getTicketNumber())) {
					sb.append("第" + (i + startRow) + "行准考证号未填写，请完善！" + ";");
				} else {
					if(1==2) {
						sb.append("第" + (i + startRow) + "行考场名称未填写，请完善！" + ";");
					}else {
						if (StringUtils.isBlank(list.get(i).getIdNumber())) {
							sb.append("第" + (i + startRow) + "行考生编号未填写，请完善！" + ";");
						} else {
										}

							if (sb.length() == 0) {
								//第四步排重验证（自身比较）
								for (int j = 0; j < list.size(); j++) {
									if (i != j) {
										if (list.get(i).getTicketNumber().equals(list.get(j).getTicketNumber())) {
											sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行准考证号重复，重复值：" + list.get(i).getIdNumber() + ";");
										}
									}
								}

								//第六步排重验证（和数据库比较），根据考生名称、考生身份证号码、该场考试的认证批次判断该考生是否已报名该考试
								StuSignUpComDO stuSignUpDO = stuSignUpService.findOneByKv("name", list.get(i).getName(), "id_number", list.get(i).getIdNumber(), "cbatch_id", Long.parseLong(cbatchId));
								if (stuSignUpDO != null) {
									sb.append("第" + (i + startRow) + "行考生已报名该次考试！" + ";");
								}

							}

						}
					}
				}

			if (sb.length() > 0) {
				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
				errorCodeVo.setSeq(cout);
				cout += 1;
				errorCodeVo.setErrorCode(sb.toString());
				list1.add(errorCodeVo);
			} else {
				if (rrUserDo != null) {
					boolean cc = userService.insertNoPW(rrUserDo);
					if (!cc) {
					}
				}
			}


				StuSignUpComDO stuSignUpDO1 = new StuSignUpComDO();
				//stuSignUpDO1.setUserId(list.get(i).getTicketNumber());//准考证号
				stuSignUpDO1.setName(list.get(i).getName());//姓名
				stuSignUpDO1.setIdNumber(list.get(i).getIdNumber());//身份证号码
				stuSignUpDO1.setCbatchId(Long.parseLong(cbatchId));//认证批次id
				stuSignUpDO1.setSignUpTime(new Date());//报名时间

				stuSignUpDO1.setType(0);
				stuSignUpDO1.setState(3);//默认已分配

			stuSignUpDO1.setTypes(type);
		/*	if(type==3){
				stuSignUpDO1.setCourt("A");
			}else {
				stuSignUpDO1.setCourt2(list.get(i).getCourt());
			}*/

			stuSignUpDO1.setUnitName(list.get(i).getUnitName());
			stuSignUpDO1.setTeacher(list.get(i).getTeacherName());


				stuSignUpDO1.setTicketNumber(list.get(i).getTicketNumber());//考号

				stuSignUpDO1.setCheckerId(this.getUserId());//默认审核人为导入者
				stuSignUpDO1.setCheckerDate(new Date());//默认审核时间为导入时间
				upDOList.add(stuSignUpDO1);

			}

		if (list1.size() == 0) {
			boolean c = stuSignUpService.insertBatch(upDOList, upDOList.size());
			if (c) {
				ExaminationBatchDO examinationBatchDOs = examinationBatchService.findOneByKv("cbatch_id", Long.parseLong(cbatchId), "type", 1);


				return Result.ok("成功导入" + list.size() + "条数据");
			} else {

				return Result.fail("报名信息导入错误，请稍后重试或联系管理员");
			}
		} else {


			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			//将list1存到缓存中
			EhCacheUtil.put("stuSignComUp" + this.getUserId(), jsonArray);
			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}
		}

	/**
	 * 第二次加密选手导出信息
	 *
	 * @param response
	 */
	@GetMapping("/downloadImportStu")
	@RequiresPermissions("jzweb:stuSignUpCom:import")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response,StuSignUpComDO stuSignUpComDTO) {
		Map map =new HashMap();
/*		if (!stuSignUpComDTO.getCompetitionType().equals("") && !stuSignUpComDTO.getCompetitionType().equals(null)){
			map.put("competitionType",stuSignUpComDTO.getCompetitionType());
		}*/
		//ExaminationBatchDO examinationBatchDO = examinationBatchService.selectById();
		map.put("cbatchId",stuSignUpComDTO.getCbatchId());
		List<StuSignUpComDO> list = stuSignUpComService.selectPageListExcel(map);
		List<StuSignUpComNum2BVo> list1 = new LinkedList<>();
		String fileName = "";
		String num1 = "";
		String num2 = "";
		for(StuSignUpComDO li:list){
			StuSignUpComNum2BVo stuSignUpComVo=new StuSignUpComNum2BVo();
			if (stuSignUpComDTO.getPermsType()==1){
				fileName = "B1第二次加密导出";
				num1 = li.getRealityNm1();
				num2 = li.getRealityNm2();

			} else if (stuSignUpComDTO.getPermsType()==2) {
				fileName = "B2第二次加密导出";
				num1 = li.getRealityNm3();
				num2 = li.getRealityNm4();
			}
			stuSignUpComVo.setNum1(num1);
			stuSignUpComVo.setNum2(num2);
			list1.add(stuSignUpComVo);
		}
		//导出操作
		EasyPoiUtil.exportExcel(list1, fileName, fileName, StuSignUpComNum2VoSC.class, "实操第二次加密导出", response);
	}
}
